package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.BuildReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.BuildReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IBuildReplyService;
import com.example.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class BuildReplyServiceImpl implements IBuildReplyService {

    @Resource
    private BuildReplyMapper buildReplyMapper;

    @Resource
    private IArticleReplyService articleReplyService;

    @Override
    public void createBuildReply(BuildReply buildReply) {
        // 评论存在性检查
        if (buildReply == null || buildReply.getArticleId() == null
                || buildReply.getPostUserId() == null || buildReply.getSenderId() == null
                || buildReply.getReceiverId() == null || buildReply.getReplyReplyId() == null
                || StringUtil.isEmpty(buildReply.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        // 设置默认值
        buildReply.setLikeCount(0);
        buildReply.setIs_deleted((byte) 0);
        Date now = new Date();
        buildReply.setCreateTime(now);

        int row = buildReplyMapper.insertSelective(buildReply);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        articleReplyService.addOneBuildReplyCountById(buildReply.getReplyReplyId());
        log.info("创建楼中楼成功，文章id{}，楼主id{}，发送者id{}，接收者id{},对应文章回复表id{},",
                buildReply.getArticleId(),buildReply.getPostUserId(),
                buildReply.getSenderId(),buildReply.getReceiverId(),
                buildReply.getReplyReplyId());
    }

    @Override
    public List<BuildReply> selectByBuildId(Long ar_id) {
        if (ar_id == null || ar_id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        return buildReplyMapper.selectByBuildId(ar_id);
    }
}
